package com.btex.app.pager;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;

import com.btex.app.Config;
import com.btex.app.OTCOrderdetailActivity;
import com.btex.app.R;
import com.btex.app.adapter.MyOrderAllAdapter;
import com.btex.app.entity.MyOrderListInfo;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.google.gson.Gson;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;

/**
 * @author zy zhangyi <zhangyi, 1104745049@QQ.com
 * @version v1.0
 * @project study1
 * @Description
 * @encoding UTF-8
 * @date 2018/8/20
 * @time 上午11:03
 * @修改记录 <pre>
 * 版本       修改人         修改时间         修改内容描述
 * --------------------------------------------------
 * <p>
 * --------------------------------------------------
 * </pre>
 */

public class MyOrderPayFragment extends Fragment implements SwipeRefreshLayout.OnRefreshListener {

    @BindView(R.id.my_otc_order_recy)
    RecyclerView mMyOtcOrderRecy;
    Unbinder unbinder;
    @BindView(R.id.my_otc_order_swipe)
    SwipeRefreshLayout mMyOtcOrderSwipe;
    @BindView(R.id.my_otc_order_recy_lin)
    LinearLayout mMyOtcOrderRecyLin;
    private MyOrderAllAdapter mMyOrderAllAdapter;
    public boolean isShow = false;
    public int page = 1;
    public boolean isLoadMore = false;
    public String otcType = "USDT_CNY";

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.otc_my_order_all, null);
        unbinder = ButterKnife.bind(this, view);

        if (!EventBus.getDefault().isRegistered(this)) {//加上判断
            EventBus.getDefault().register(this);

        }
        return view;

    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        mMyOtcOrderSwipe.setOnRefreshListener(this);


        initAdapter();
        initOtcData();


    }

    private void initAdapter() {

        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getContext());
        mMyOtcOrderRecy.setLayoutManager(linearLayoutManager);

        mMyOrderAllAdapter = new MyOrderAllAdapter(null);
        mMyOtcOrderRecy.setAdapter(mMyOrderAllAdapter);
        mMyOrderAllAdapter.setEnableLoadMore(true);

    }


    private void initOtcData() {

        if (mMyOtcOrderSwipe != null) {
            mMyOtcOrderSwipe.setRefreshing(true);
        }
        int num = (int) ((Math.random() * 9 + 1) * 100000);

        OkGo.<String>get(Config.GET_OTC_TRADES_HIS + "?rnd=" + String.valueOf(num)).params("pair", otcType).params("trade_status", "1").params("page", String.valueOf(page)).params("page_size", "20").execute(new StringCallback() {
            @Override
            public void onSuccess(Response<String> response) {
                if (mMyOtcOrderSwipe != null) {
                    mMyOtcOrderSwipe.setRefreshing(false);
                }

                String result = response.body().toString();
                try {
                    JSONObject jsonObject = new JSONObject(result);
                    if (jsonObject.getString(Config.KEY_CODE).equals("1")) {
                        Gson gson = new Gson();
                        MyOrderListInfo myOrderListInfo = gson.fromJson(result, MyOrderListInfo.class);
                        List<MyOrderListInfo.DataBean> data = myOrderListInfo.getData();
                        initOtcView(data);
                    }

                } catch (JSONException e) {
                    e.printStackTrace();

                }

            }
        });


//        SharedPreferencesUtil sharedPreferences = SharedPreferencesUtil.getSharedPreferences(getActivity());
//        PreferencesCookieStore cookieStore = CookieTool.getCookieStore(MyApplication.getContextObject(), sharedPreferences);
//        RequestParams params = new RequestParams();
//        params.addQueryStringParameter("pair", otcType);
//        params.addQueryStringParameter("trade_status", "1");
//        params.addQueryStringParameter("page", String.valueOf(page));
//        params.addQueryStringParameter("page_size", "20");
//
//
//        new HttpUtils().configCookieStore(cookieStore).send(HttpRequest.HttpMethod.GET, Config.GET_OTC_TRADES_HIS + "?rnd=" + String.valueOf(num), params, new RequestCallBack<String>() {
//            @Override
//            public void onSuccess(ResponseInfo<String> responseInfo) {
//                if (mMyOtcOrderSwipe != null) {
//                    mMyOtcOrderSwipe.setRefreshing(false);
//                }
//                String result = responseInfo.result;
//                try {
//                    JSONObject jsonObject = new JSONObject(result);
//                    if (jsonObject.getString(Config.KEY_CODE).equals("1")) {
//                        Gson gson = new Gson();
//                        MyOrderListInfo myOrderListInfo = gson.fromJson(result, MyOrderListInfo.class);
//                        List<MyOrderListInfo.DataBean> data = myOrderListInfo.getData();
//                        initOtcView(data);
//                    }
//
//                } catch (JSONException e) {
//                    e.printStackTrace();
//
//                }
//            }
//
//            @Override
//            public void onFailure(HttpException error, String msg) {
//
//            }
//        });
    }

    private void initOtcView(List<MyOrderListInfo.DataBean> data) {


        if (mMyOtcOrderRecy != null && mMyOrderAllAdapter != null) {


            if (data.size() <= 0) {

                if (isLoadMore) {
                    mMyOrderAllAdapter.loadMoreEnd();
                    mMyOtcOrderRecyLin.setVisibility(View.GONE);
                    mMyOtcOrderRecy.setVisibility(View.VISIBLE);
                } else {
                    mMyOrderAllAdapter.setEmptyView(R.layout.otc_order_empty, mMyOtcOrderRecy);
                    mMyOtcOrderRecyLin.setVisibility(View.VISIBLE);
                    mMyOtcOrderRecy.setVisibility(View.GONE);
                }
                return;

            } else {

                mMyOtcOrderRecyLin.setVisibility(View.GONE);
                mMyOtcOrderRecy.setVisibility(View.VISIBLE);
                if (isShow) {
                    mMyOrderAllAdapter.setNewData(data);

                }

                if (isLoadMore) {

                    if (data.size() <= 0) {
                        mMyOrderAllAdapter.loadMoreEnd();
                    } else {
                        mMyOrderAllAdapter.loadMoreComplete();
                    }

                    mMyOrderAllAdapter.addData(data);


                }

                if (!isShow && !isLoadMore) {
                    mMyOrderAllAdapter.setNewData(data);
                }
            }


            mMyOrderAllAdapter.setOnLoadMoreListener(new BaseQuickAdapter.RequestLoadMoreListener() {
                @Override
                public void onLoadMoreRequested() {
                    page++;
                    isLoadMore = true;
                    isShow = false;
                    initOtcData();
                }
            }, mMyOtcOrderRecy);


            mMyOrderAllAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
                @Override
                public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                    MyOrderListInfo.DataBean dataBean = (MyOrderListInfo.DataBean) adapter.getData().get(position);
                    String order_id = dataBean.getTrade_id();
                    startActivity(new Intent(getActivity(), OTCOrderdetailActivity.class).putExtra("data", order_id));
                }
            });

        }

    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        EventBus.getDefault().unregister(this);
        unbinder.unbind();
    }

    @Override
    public void onRefresh() {
        // TODO: 2018/8/20 数据刷新
        isShow = true;
        isLoadMore = false;
        page = 1;
        initOtcData();

    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void MyOrderPayFragment(String event) {


        isShow = true;
        isLoadMore = false;
        page = 1;
        otcType = event;
        initOtcData();

//        if (event.equals("Orderusdt")) {
//            isShow = true;
//            isLoadMore = false;
//            page = 1;
//            otcType = "USDT_CNY";
//            initOtcData();
//
//        }
//        if (event.equals("Ordertyd")) {
//            isShow = true;
//            isLoadMore = false;
//            page = 1;
//            otcType = "TYD_TYZ";
//            initOtcData();
//
//        }


    }

}
